package kr.co.redcircle.broker.handler.worker;

import kr.co.redcircle.broker.Broker;
import kr.co.redcircle.broker.information.NodeInformation;
import kr.co.redcircle.broker.io.BrokerRequest;
import kr.co.redcircle.broker.io.BrokerResponse;
import kr.co.redcircle.broker.io.IHandler;
import kr.co.redcircle.broker.io.net.Unicast.UnicastNetworkService;
import kr.co.redcircle.broker.registry.Registry;
import kr.co.redcircle.broker.utility.JsonUtility;
import net.sf.json.JSONObject;

public class AddWorkerNodeResponseHandler implements IHandler {

	@Override
	public BrokerResponse invoke(String respString) {
		BrokerRequest jObj = JsonUtility.getBrokerRequest(respString);
		
		JSONObject paramObject = JSONObject.fromObject(jObj.get(Broker.PARAMETERS));
		
		System.out.println("AddWorkerNodeResponseHandler.paramObject : " + paramObject.toString());
		
		if (paramObject != null && (Boolean)paramObject.get(Broker.RESULT)){
			
			System.out.println("regist name node information~! : " + paramObject.getJSONObject(Broker.HOST).toString());
			Registry.setNodeInformation(Broker.BROKER_NAMENODE_INFORMATION, new NodeInformation(paramObject.getJSONObject(Broker.HOST)));			
			
			JSONObject param = new JSONObject();
			param.put(Broker.IP, UnicastNetworkService.getHOST());
			param.put(Broker.PORT, UnicastNetworkService.getPORT());
			param.put(Broker.CID_S, Registry.getCID());
			
			// build BrokerRequest object
			BrokerRequest request = new BrokerRequest();
			request.put(Broker.FROM, Registry.getCID());
			request.put(Broker.TO, "NAME");
			request.put(Broker.BUSINESS_S, "worker");
			request.put(Broker.METHOD, "registBusiness");
			request.put(Broker.PARAMETERS, param);
	
			JSONObject hostObject = paramObject.getJSONObject(Broker.HOST);
			String ip = hostObject.getString(Broker.IP);
			int port = hostObject.getInt(Broker.PORT);
			
			// unicast only~!
			Registry.sendUnicast(ip , port, request);
		}
		
		return null;
	}

}
